package cn.fl.custpay.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import cn.lb.framework.poi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.custpay.condition.CmmEmppayRecordQueryCondition;
import cn.fl.custpay.service.ICmmEmppayRecordService;
import cn.fl.custpay.vo.CmmEmppayRecordVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 用户扣款记录 控制层
 */
@Controller
@RequestMapping("/custpay/cmmEmppayRecord")
public class CmmEmppayRecordController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmmEmppayRecordController.class);

	/**
	 * CmmEmppayRecord 服务层BEAN
	 */
	@Autowired
	private ICmmEmppayRecordService cmmEmppayRecordService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toCmmEmppayRecordListPage.do", method = { RequestMethod.GET})
	public ModelAndView toCmmEmppayRecordListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("custpay/cmmEmppayRecord/cmmEmppayRecordList");
		List<Map<String,String>> statuslist = new ArrayList<Map<String,String>>();
		Map<String,String> typemap1 = new HashMap<String,String>();
		typemap1.put("key","0");
		typemap1.put("value","失败");
		statuslist.add(typemap1);
		Map<String,String> typemap2 = new HashMap<String,String>();
		typemap2.put("key","1");
		typemap2.put("value","成功");
		statuslist.add(typemap2);
		Map<String,String> typemap3 = new HashMap<String,String>();
		typemap3.put("key","2");
		typemap3.put("value","未支付");
		statuslist.add(typemap3);
		Map<String,String> typemap4 = new HashMap<String,String>();
		typemap4.put("key","3");
		typemap4.put("value","已受理");
		statuslist.add(typemap4);
		view.addObject("statuslist", statuslist);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("custpay/cmmEmppayRecord/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initCmmEmppayRecordList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCmmEmppayRecordList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String orderid = request.getParameter("orderid");
		String isSuc = request.getParameter("isSuc");
		String usrNm = request.getParameter("usrNm");
		String rlNm = request.getParameter("rlNm");
		String platformSeqId = request.getParameter("platformSeqId");
		String crtTmBegin = request.getParameter("crtTmBegin");
		String crtTmEnd = request.getParameter("crtTmEnd");
		String isAutoCharge = request.getParameter("isAutoCharge");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CmmEmppayRecordQueryCondition qc = new CmmEmppayRecordQueryCondition();
		if (StringUtils.isNotEmpty(orderid)) {
			qc.setId(Long.valueOf(orderid));
		}
		if (StringUtils.isNotEmpty(isSuc)) {
			qc.setIsSuc(Integer.valueOf(isSuc));
		}
		if (StringUtils.isNotEmpty(usrNm)) {
			qc.setUsrNm(usrNm);
		}
		if (StringUtils.isNotEmpty(platformSeqId)) {
			qc.setPlatformSeqId(platformSeqId);
		}
		if (StringUtils.isNotEmpty(rlNm)) {
			qc.setRlNm(rlNm);
		}
		if (StringUtils.isNotEmpty(crtTmBegin)) {
			qc.setCrtTmBegin(DateUtils.formatStringToDate(crtTmBegin,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(isAutoCharge)) {
			qc.setIsAutoCharge(Integer.valueOf(isAutoCharge));
		}

		page.setCondition(qc);
		
		//TODO SOMETHING
		Pager pager = this.cmmEmppayRecordService.searchListPage(page);
		List<CmmEmppayRecordVO> list = (List<CmmEmppayRecordVO>)pager.getResultList();
		Map<String,String> sumap = new HashMap<String,String>();
		sumap.put("0","失败");
		sumap.put("1","成功");
		sumap.put("2","未支付");
		sumap.put("3","已受理");
		Map<String,String> paytypemap = new HashMap<String,String>();
		paytypemap.put("1","汇付");
		paytypemap.put("2","信联");
		paytypemap.put("3","国付宝");
		Map<String,String> paymenttypemap = new HashMap<String,String>();
		paymenttypemap.put("1","快捷支付");
		paymenttypemap.put("2","代扣支付");
		Map<String,String> isautochargemap = new HashMap<String,String>();
		isautochargemap.put("1","是");
		isautochargemap.put("0","否");
		Map<String,String> freetypemap = this.cmmEmppayRecordService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd(),"PRJ0026");
		for(CmmEmppayRecordVO _vo : list){
			if(null != _vo.getIsSuc()){
				_vo.setIsSucNm(sumap.get(String.valueOf(_vo.getIsSuc())));
			}
			Long paymentmoney = _vo.getPaymentMoney()!=null?_vo.getPaymentMoney():0l;
			if(null != _vo.getPaymentMoney()){
				_vo.setPaymentMoneydou(DecimalUtils.convertFenToYuan(_vo.getPaymentMoney()));
			}
			if(StringUtils.isNotEmpty(_vo.getCommAmt())){
				_vo.setCommAmt(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getCommAmt()))));
			}
			if(StringUtils.isNotEmpty(_vo.getPayComm())){
				_vo.setPayComm(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getPayComm()))));
			}
			if(null != _vo.getPayType()){
				_vo.setPayTypeNm(paytypemap.get(String.valueOf(_vo.getPayType())));
			}
			if(null != _vo.getPaymentType()){
				_vo.setPaymentTypeNm(paymenttypemap.get(String.valueOf(_vo.getPaymentType())));
			}
			if(null != _vo.getIsAutoCharge()){
				_vo.setIsAutoChargeNm(isautochargemap.get(String.valueOf(_vo.getIsAutoCharge())));
			}
			if(StringUtils.isNotEmpty(_vo.getFeeAmtMn())){
				_vo.setFeeAmtMndou(DecimalUtils.convertFenToYuan(_vo.getFeeAmtMn()));
			}
			if(StringUtils.isNotEmpty(_vo.getFeeTypCd())){
				_vo.setFeeTypCdNm(freetypemap.get(_vo.getFeeTypCd()));
			}
		}
		ListPageVO<CmmEmppayRecordVO> listPage = new ListPageVO<CmmEmppayRecordVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.cmmEmppayRecordService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CmmEmppayRecordVO vo = this.cmmEmppayRecordService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CmmEmppayRecordVO entity = null;
		try {
			entity = new CmmEmppayRecordVO();
			//TODO ADD PARAM
			Long id = this.cmmEmppayRecordService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CmmEmppayRecordVO entity = null;
		try {
			entity = new CmmEmppayRecordVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.cmmEmppayRecordService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	@RequestMapping(value = "/exportCmmEmppayRecordExcel.do", method = {RequestMethod.POST, RequestMethod.GET})
	public void exportCmmEmppayRecordExcel(HttpServletRequest request, HttpServletResponse response) {
		String orderid = request.getParameter("orderid");
		String isSuc = request.getParameter("isSuc");
		String usrNm = request.getParameter("usrNm");
		String rlNm = request.getParameter("rlNm");
		String platformSeqId = request.getParameter("platformSeqId");
		String crtTmBegin = request.getParameter("crtTmBegin");
		String crtTmEnd = request.getParameter("crtTmEnd");
		String isAutoCharge = request.getParameter("isAutoCharge");

		CmmEmppayRecordQueryCondition qc = new CmmEmppayRecordQueryCondition();
		if (StringUtils.isNotEmpty(orderid)) {
			qc.setId(Long.valueOf(orderid));
		}
		if (StringUtils.isNotEmpty(isSuc)) {
			qc.setIsSuc(Integer.valueOf(isSuc));
		}
		if (StringUtils.isNotEmpty(usrNm)) {
			qc.setUsrNm(usrNm);
		}
		if (StringUtils.isNotEmpty(platformSeqId)) {
			qc.setPlatformSeqId(platformSeqId);
		}
		if (StringUtils.isNotEmpty(rlNm)) {
			qc.setRlNm(rlNm);
		}
		if (StringUtils.isNotEmpty(crtTmBegin)) {
			qc.setCrtTmBegin(DateUtils.formatStringToDate(crtTmBegin,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(isAutoCharge)) {
			qc.setIsAutoCharge(Integer.valueOf(isAutoCharge));
		}
		List<CmmEmppayRecordVO> list = this.cmmEmppayRecordService.searchList(qc);
		Map<String,String> sumap = new HashMap<String,String>();
		sumap.put("0","失败");
		sumap.put("1","成功");
		sumap.put("2","未支付");
		sumap.put("3","已受理");
		Map<String,String> paytypemap = new HashMap<String,String>();
		paytypemap.put("1","汇付");
		paytypemap.put("2","信联");
		paytypemap.put("3","国付宝");
		Map<String,String> paymenttypemap = new HashMap<String,String>();
		paymenttypemap.put("1","快捷支付");
		paymenttypemap.put("2","代扣支付");
		Map<String,String> isautochargemap = new HashMap<String,String>();
		isautochargemap.put("1","是");
		isautochargemap.put("0","否");
		Map<String,String> freetypemap = this.cmmEmppayRecordService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd(),"PRJ0026");
		for(CmmEmppayRecordVO _vo : list){
			if(null != _vo.getIsSuc()){
				_vo.setIsSucNm(sumap.get(String.valueOf(_vo.getIsSuc())));
			}
			Long paymentmoney = _vo.getPaymentMoney()!=null?_vo.getPaymentMoney():0l;
			if(null != _vo.getPaymentMoney()){
				_vo.setPaymentMoneydou(DecimalUtils.convertFenToYuan(_vo.getPaymentMoney()));
			}
			if(StringUtils.isNotEmpty(_vo.getCommAmt())){
				_vo.setCommAmt(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getCommAmt()))));
			}
			if(StringUtils.isNotEmpty(_vo.getPayComm())){
				_vo.setPayComm(String.valueOf(DecimalUtils.convertFenToYuan(Long.valueOf(_vo.getPayComm()))));
			}
			if(StringUtils.isNotEmpty(_vo.getFeeAmtMn())){
				_vo.setFeeAmtMndou(DecimalUtils.convertFenToYuan(_vo.getFeeAmtMn()));
			}
			if(null != _vo.getPayType()){
				_vo.setPayTypeNm(paytypemap.get(String.valueOf(_vo.getPayType())));
			}
			if(null != _vo.getPaymentType()){
				_vo.setPaymentTypeNm(paymenttypemap.get(String.valueOf(_vo.getPaymentType())));
			}
			if(null != _vo.getIsAutoCharge()){
				_vo.setIsAutoChargeNm(isautochargemap.get(String.valueOf(_vo.getIsAutoCharge())));
			}
			if(StringUtils.isNotEmpty(_vo.getFeeTypCd())){
				_vo.setFeeTypCdNm(freetypemap.get(_vo.getFeeTypCd()));
			}
		}
		ExportParams params = new ExportParams("扣款记录", "扣款记录", ExcelType.HSSF);
		//HSSF是POI工程对Excel 97(-2007)文件操作的纯Java实现;
		//XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现
		//SXSSF基于XSSF的低内存占用的API
		params.setColor(HSSFColor.BRIGHT_GREEN.index);//表头颜色
		params.setStyle(ExcelExportStylerDefaultImpl.class);//ExcelExportStylerBorderImpl 有边框样式 ExcelExportStylerColorImpl  有边框间隔行样式 ExcelExportStylerDefaultImpl	默认的样式
		Workbook workbook = ExcelExportUtil.exportExcel(params, CmmEmppayRecordVO.class, list);
		OutputStream ouputStream = null;
		try {
			String filename="扣款记录";
			filename=new String(filename.getBytes("UTF-8"),"ISO8859-1");
			response.reset();
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");// 设定输出文件头
			response.setContentType("application/x-msdownload");// 定义输出类型
			ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (UnsupportedEncodingException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		} catch (IOException e) {
			BaseLogUtils.error(logger, "-", "异常", e);
		}finally {
			//关闭流
			if(ouputStream!=null){
				try {
					ouputStream.close();
				} catch (IOException e) {
					BaseLogUtils.error(logger, "-", "异常", e);
				}
			}
		}
	}
}

